#-*- coding:utf8 -*-
import config
import time
from lib.session import Session
from base import BaseHandler
from lib import verify
import hashlib
import urllib
import json

class IndexHandler(BaseHandler):
    
    def initialize(self, method = ''):
        self.__method = method
    
    def get(self):
        islogin = self.get_current_user()
        if self.__method == 'logout':
            if islogin:
                s = Session(self)
                s.destroy()
            return self.redirect('/')
        
        if islogin:
            if self.__method == 'dynamic':
                return self.__dynamic()
            elif self.__method == 'last':
                return self.__last()
            return self.__index()
        else:
            nexturl = urllib.unquote_plus(self.get_argument('next', '/'))
            self.display('main.html', msg = [], email = '', nexturl = nexturl)
            
    def __dynamic(self):
        max_id = int(self.get_argument('id', 0)) + 1
        rows = self.__query_index({'id': max_id, 'direction': 1, 'limit': 50})
        if rows == None or len(rows) == 0:
            return self.write(json.dumps([max_id, '']))
        str = self.fetch('dynamic.html', questions=rows['rows'])
        self.write(json.dumps([rows['max_id'], str]))
        
    def __last(self):
        min_id = int(self.get_argument('id', 0)) - 1
        rows = self.__query_index({'id': min_id, 'direction': 2, 'limit': 10})
        if min_id <= 0 or rows == None or len(rows) == 0:
            return self.write(json.dumps([min_id, '']))
        str = self.fetch('dynamic.html', questions=rows['rows'])
        self.write(json.dumps([rows['min_id'], str]))
            
    def __index(self):
        conn = config.getDBConnect()
        try:
            s = Session(self)
            rtn = self.__query_index({'id': 1, 'direction': 1, 'limit': 15})
            recommend = self.__get_recommend(conn)
            topics = self.__get_topics(conn)
            self.display('index.html', questions=rtn['rows'], user=s, res=recommend, max_id = rtn['max_id'], min_id = rtn['min_id'], topics=topics)
        except:
            self.write("index template error!")
    
    def post(self):
        if self.__method == 'login':
            self.__login()
        else:
            self.redirect('/')
    
    def __login(self):
        email = self.get_argument('email', '')
        nexturl = self.get_argument('nexturl', '/')
        pwd = hashlib.new("md5", self.get_argument('password', '')).hexdigest()
        msg = []
        islogin = False
        uid = 0
        name = ''
        if not verify.IsEmail(email):
            msg.append(u"请输入正确的邮箱地址")
        else:    
            sql = "SELECT `id`,`password`,`name` FROM `user` WHERE `email` = '%s'" %(email)
            conn = config.getDBConnect()
            try:
                row = conn.get(sql)
                if not row:
                    msg.append(u"邮箱地址不存在")
                elif row['password'] <> pwd:
                    msg.append(u"密码错误")
                else:
                    islogin = True
                    uid = row['id']
                    name = row['name']
            except:
                msg.append(u"系统错误")
          
        if not islogin:
            self.display('main.html', msg=msg, email=email, nexturl = nexturl)
        else:
            s = Session(self)
            s.put('login', True)
            s.put('uid', uid)
            s.put('name', name)
            s.put('pinyin', name)
            self.redirect(nexturl)
    
    # direction: 1 取得大于等于当前id的n个数
    # direction: 2 取得小于等于当前id的n个数
    def __query_index(self, args={'id':-1, 'direction':1, 'limit':20}):
        s = Session(self)
        uid = int(s.get('uid'))
        sql_id = ""
        if (args['id'] > 0):
            if args['direction'] == 1:
                sql_id = "a.`id` >= %d and "% int(args['id'])
            else:
                sql_id = "a.`id` <= %d and "% int(args['id'])

        sql = "SELECT a.`id`, a.`cid`, a.`title`, a.`cnt_answer`, a.`best`, "\
            "b.name, b.icon, IFNULL(c.`status`, -1) as `follow` FROM `question` a "\
            "LEFT JOIN `question_fans` c ON a.`id`=c.`id_question` "\
            "and c.`id_user`=%d, user b WHERE %s"\
            "a.id_user = b.id ORDER BY id DESC LIMIT %d" %(uid, sql_id, int(args['limit']))
        conn = config.getDBConnect()
        rtn = {'rows':[], 'min_id':0, 'max_id':0}
        try:
            rows = conn.query(sql)
            max_id = 0
            min_id = -1
            for row in rows:
                self.__get__answer_user(conn, row)
                self.__get_best_answer(conn, row)
                if row.id > max_id:
                    max_id = row.id
                if min_id == -1:
                    min_id = row.id
                if row.id < min_id:
                    min_id = row.id
            rtn['rows']=rows
            rtn['max_id']=max_id
            rtn['min_id']=min_id
            return rtn
        except:
            return rtn
            
    def __get__answer_user(self, conn, question):
        sql = "SELECT b.`name` FROM `answer` a, `user` b where a.`id_question` = %d "\
                    "and a.`id_user` = b.`id`" %(question.id)
        try:
            rows = conn.query(sql)
            question['agree_user'] = rows
        except:
            question['agree_user'] = []
            return 
    
    def __get_best_answer(self, conn, question):
        s = Session(self)
        uid = int(s.get('uid'))
        sql = "SELECT a.`id`, a.id_user, a.`content`, a.`tm_add`, a.`cnt_agree`, a.cnt_comment, "\
                "b.`id` AS uid, b.`name`, b.`signature`, IFNULL(c.`status`, 0) as `status`, "\
                "IFNULL(d.`status`, 0) as `thank`, IFNULL(e.`status`, 0) as `nohelp` "\
                "FROM `answer` AS a LEFT JOIN `user` AS b ON a.`id_user` = b.`id` "\
                "LEFT JOIN answer_vote as c on a.id = c.id_answer and c.id_user=%d "\
                "LEFT JOIN answer_attr as d on a.id = d.id_answer and d.id_user=%d and d.type = 0 "\
                "LEFT JOIN answer_attr as e on a.id = e.id_answer and e.id_user=%d and e.type = 1 "\
                "WHERE a.`id` = %d" %(uid, uid, uid, question.best)
        try:
            row = conn.get(sql)
            if not row:
                question.best = 0
            else:
                row['time'] = time.strftime("%Y-%m-%d", time.localtime(row.tm_add))
                row['votes'] = self.__query_answer_vote(conn, question.best)
                question['answer'] = row
                
        except:
            question.best = 0
    
    def __get_recommend(self, conn):
        sql = "select `id`, `name`, `icon`, `cnt_myanswer` from `user` limit 10"
        try:
            rows = conn.query(sql)
            return rows
        except:
            return []
    
    def __get_topics(self, conn):
        sql = "select `id`, `name` from `topic` limit 10"
        try:
            rows = conn.query(sql)
            return rows
        except:
            return []
        
    def __query_answer_vote(self, conn, aid):
        sql = "SELECT a.`id_user`, b.`name` FROM `answer_vote` a, `user` b "\
                "WHERE a.`id_answer`=%d and a.`status` = 1 and a.`id_user` = b.`id` limit 3"%(aid)
        try:
            rows = conn.query(sql)
            return rows
        except:
            return []
        